/*
 * Copyright (c) 2007 Aleksey Nikiforov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of 'Aleksey Nikiforov' nor the names of other contributors 
 *   may be used to endorse or promote products derived from this software 
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.lex.input.mouse;


import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.lex.input.mouse.component.AdvancedMouse;
import org.lex.input.mouse.component.SelectableNativeMouse;

import com.jme.input.InputHandler;
import com.jme.input.MouseInput;
import com.jme.input.MouseInputListener;
import com.jme.input.action.InputAction;
import com.jme.input.action.InputActionEvent;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;


/**
 * You can extend this class to add more functionality and to override
 * the default mouse listener that feeds the events to
 * all the attached listeners.
 * 
 * setCursor() methods will not raise an exception when setting a null cursor.
 * If your cursors do not appear on the screen, check if those cursor
 * were actually loaded.
 * 
 * @author lex
 *
 */
public class MouseManager implements SelectableNativeMouse {

	private static final Logger log =
			Logger.getLogger(MouseManager.class.getName());
	
	
	protected AdvancedMouse mouse;
	protected SelectableNativeMouse selectableMouse;
	
	protected Map<String, Cursor> cursors = new HashMap<String, Cursor>();
	protected String currentCursor;
	
	private Vector3f delta = new Vector3f();
	protected MouseInput mouseInput = MouseInput.get();
	protected InputHandler currentHandler;
	
	protected List<MouseInputListener> listeners;
	
	private InputAction updateAction = new InputAction() {
		public void performAction(InputActionEvent evt) {
			delta.x = mouseInput.getXDelta();
			delta.y = mouseInput.getYDelta();
			delta.z = mouseInput.getWheelDelta();
		}
	};
	
	private MouseInputListener mouseListener = new MouseInputListener() {
		public void onButton(int button, boolean pressed, int x, int y) {
			x = Math.round(mouse.getHotSpotPosition().x);
			y = Math.round(mouse.getHotSpotPosition().y);
			
			for (MouseInputListener listener : listeners) {
				listener.onButton(button, pressed, x, y);
			}
		}
		public void onMove(int xDelta, int yDelta, int newX, int newY) {
			int x = Math.round(mouse.getHotSpotPosition().x);
			int y = Math.round(mouse.getHotSpotPosition().y);
			
			for (MouseInputListener listener : listeners) {
				listener.onMove(xDelta, yDelta, x, y);
			}
		}
		public void onWheel(int wheelDelta, int x, int y) {
			x = Math.round(mouse.getHotSpotPosition().x);
			y = Math.round(mouse.getHotSpotPosition().y);
			
			for (MouseInputListener listener : listeners) {
				listener.onWheel(wheelDelta, x, y);
			}
		}
	};

	public MouseManager(AdvancedMouse mouse) {
		this.mouse = mouse;
		if (mouse instanceof SelectableNativeMouse) {
			selectableMouse = (SelectableNativeMouse) mouse;
		}
		
		listeners = new ArrayList<MouseInputListener>(1);
		setInterceptListener(mouseListener);
	}
	
	protected void setInterceptListener(MouseInputListener listener) {
		if (mouseListener != null) {
			mouseInput.removeListener(mouseListener);
		}
		
		mouseListener = listener;
		mouseInput.addListener(mouseListener);
	}
	
	public void registerWithInputHandler(InputHandler inputHandler) {
		if (currentHandler != null) {
            currentHandler.removeAction(updateAction);
        }
		
		currentHandler = inputHandler;
		
		inputHandler.addAction(updateAction,
	        	InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 0, true);
		
		mouse.registerWithInputHandler(inputHandler);
	}
	
	public AdvancedMouse getMouse() {
		return mouse;
	}
	
	public void reinit(int width, int height) {
		mouse.reinit(width, height);
	}
	
	public Vector3f getDelta() {
		return delta;
	}
	
	public Vector2f getMousePosition() {
		return mouse.getHotSpotPosition();
	}
	
	public void setMousePosition(float x, float y) {
		mouse.setHotSpotPosition(x, y);
	}

	public void setCursor(String name, String resource) {
		URL file = this.getClass().getClassLoader().getResource(resource);
		setCursor(name, file);
	}
	
	/**
	 * Set a cursor to be used later via useCursor(name).
	 * @see net.mindgamer.risetothestars.common.mousemanager.Cursor#load(java.lang.String, java.net.URL, java.lang.String)
	 * 
	 * @param name
	 * @param file
	 */
	public void setCursor(String name, URL file) {
		Cursor cursor = Cursor.load(file);
		if (cursor == null) {
			log.log(Level.INFO, "Unable to load the cursor \"{0}\".", file);
			return;
		}
		
		cursors.put(name, cursor);
	}
	
	/**
	 * Set a cursor to be used later via useCursor(name).
	 * 
	 * @see net.mindgamer.risetothestars.common.mousemanager.Cursor#load(java.lang.String, java.net.URL, java.lang.String)
	 * 
	 * @param name
	 * @param cursor
	 */
	public void setCursor(String name, Cursor cursor) {
		if (cursor == null) {
			log.log(Level.INFO, "Trying to set a null cursor.");
			return;
		}
		cursors.put(name, cursor);
	}

	/**
	 * Changes the cursor and makes the mouse active and visible. If the name
	 * equals to the name of the currently used cursor, the the cursor
	 * will not be set (prevents resetting the animation).
	 * The mouse is always made active and visible by the call to this
	 * method (even if the cursor is not set).
	 * 
	 * @param name the name of the cursor to use
	 */
	public void useCursor(String name) {
		if (!name.equals(currentCursor)) {
			Cursor cursor = cursors.get(name);
			mouse.setCursor(cursor);
			currentCursor = name;
		}
		mouse.enable();
	}
	
	/**
	 * @return the name of the currently used cursor
	 */
	public String getCurrentCursor() {
		return currentCursor;
	}
	
	/**
	 * Calling this method will cause the cursor to disappear.
	 * The mouse cannot leave the window in this mode.
	 */
	public void hideCursor() {
		mouse.setCursorVisible(false);
	}
	
	/**
	 * Changes the cursor and makes the mouse inactive (the cursor
	 * will not respond to device movements).
	 * @param name the name of the cursor to use
	 */
	public void useSuspendedCursor(String name) {
		mouse.setActive(false);
		if (!name.equals(currentCursor)) {
			Cursor cursor = cursors.get(name);
			mouse.setCursor(cursor);
			currentCursor = name;
		}
	}
	
	/**
	 * If the mouse passed at the costruction time does not implement
	 * the SelectableNativeMouse interface, then this method will always
	 * return false.
	 * 
	 * @see net.mindgamer.risetothestars.common.mousemanager.component.SelectableNativeMouse#isNativeMousePreferred()
	 */
	public boolean isNativeMousePreferred() {
		if (selectableMouse == null) return false;
		return selectableMouse.isNativeMousePreferred();
	}

	/**
	 * If the mouse passed at the costruction time does not implement
	 * the SelectableNativeMouse interface, then this method will exit
	 * without making any changes.
	 * 
	 * @see net.mindgamer.risetothestars.common.mousemanager.component.SelectableNativeMouse#setNativeMousePreferred(boolean)
	 */
	public void setNativeMousePreferred(boolean useNative) {
		if (selectableMouse == null) return;
		selectableMouse.setNativeMousePreferred(useNative);
	}

	/**
	 * The reported delta might not match the reported position.
	 * Example: if position was (0, 0) and delta is (5, 5) then
	 * the new position can be (10, 10) when software mouse with
	 * sensitivity 2 is in use.
	 * 
	 * You can change this behavior by extending MouseManager
	 * class and setting your own intercept listner that feeds events to
	 * all the listeners attached to the MouseManager. You can do so
	 * using a protected method setInterceptListener().
	 * 
	 * @param listener
	 */
	public void addListener(MouseInputListener listener) {
		listeners.add(listener);
	}
	
	public void removeListener(MouseInputListener listener) {
		listeners.remove(listener);
	}
	
	public float getWidth() {
		return mouse.getWidth();
	}
	
	public float getHeight() {
		return mouse.getHeight();
	}
}
